//
//  EmotionKeyboardViewModel.swift
//  weibobbaj
//
//  Created by Tiffany宝 on 16/4/27.
//  Copyright © 2016年 Tiffany. All rights reserved.
//
//  表情键盘所做的一些逻辑操作：读取表情，截取表情，保存最近表情

import UIKit

class EmotionKeyboardViewModel: NSObject {
    
    //单例
    static let sharViewModel: EmotionKeyboardViewModel = EmotionKeyboardViewModel()
    
    //沙盒路径
    private lazy var path: String = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("emotion.archiver")
    
    
    //从 Bundle包 里读取 NSBundle
    func loadBundle() -> NSBundle{
        
        let path = NSBundle.mainBundle().pathForResource("Emoticons.bundle", ofType: nil)!
        
        return NSBundle(path: path)!
    }
    
    // MARK: - 通过表情字符串找到其对应的表情模型
    func emotionWithChs(chs: String) -> EmotionModel?{
        
        //遍历默认表情
        for value in defaultEmotion{
            
            if value.chs == chs{
                return value
            }
        }
        
        //遍历浪小花表情
        for value in lxhEmotion{
            
            if value.chs == chs{
                return value
            }
        }
        
        return nil
        
    }
    
    // 定义 collectView 所需要的数组类型
    lazy var allEmotions: [[[EmotionModel]]] = {
        /*
        最近
        默认
        emoji
        浪小花
        */
        return [
            //            [[EmotionModel]()],
            [self.recentEmotions],
            self.emotionPageArray(self.defaultEmotion),
            self.emotionPageArray(self.emojiEmotion),
            self.emotionPageArray(self.lxhEmotion)
        ]
    }()
    
    //最近表情数组
    lazy var recentEmotions: [EmotionModel] = {
        
        //从沙盒中取
        if let result = NSKeyedUnarchiver.unarchiveObjectWithFile(self.path) as? [EmotionModel]{
            return result
        }else{
            //第一次读取为空
            return [EmotionModel]()
        }
        
    }()
    
    // MARK: - 存储最近表情的方法
    func saveRecentEmotins(emotion: EmotionModel){
        
        var emotions = allEmotions[0][0]
        //1.将最近的表情存储到最近表情数组
        //        allEmotions[0][0].insert(emotion, atIndex: 0)
        //        self.recentEmotions.insert(emotion, atIndex: 0)
        emotions.insert(emotion, atIndex: 0)
        
        //数组去除重复元素的方法 (filter 过滤) *** 不要在遍历的时候去移除遍历对象中的元素(牢记)
        //repeatEmotions 数组里存着最近表情中的重复表情
        let repeatEmotions = recentEmotions.filter { (value) -> Bool in
            
            if value.type == emotion.type{
                
                if value.type == "1"{
                    
                    //emoji表情,对比code,返回相同 code 的 value
                    return value.code == emotion.code
                }else{
                    return value.chs == emotion.chs
                }
            }
            return false
        }
        
        for emotion in repeatEmotions{
            
            if let index = emotions.indexOf(emotion){
                emotions.removeAtIndex(index)
            }
        }
        
        
        //2.去除重复表情 && 去除多余20的表情
        while emotions.count > 20{
            
            emotions.removeLast()
        }
        
        // *** 记得赋值回来 ***
        allEmotions[0][0] = emotions
        
        //3.使用归档的方法保存最近的表情
//        print(path)
        NSKeyedArchiver.archiveRootObject(emotions, toFile: path)
    }
    
    
    //切割表情 把108个表情 切割成20个表情为一页
    private func emotionPageArray(emotions: [EmotionModel]) -> [[EmotionModel]]{
        
        //20个表情为一页,有几页
        let pageCount = (emotions.count - 1) / 20 + 1
        
        //创建临时数组
        var tempArr: [[EmotionModel]] = [[EmotionModel]]()
        
        for i in 0..<pageCount {
            
            //分组
            //从哪里开始截取
            let loc = i * 20
            
            //截取多少
            var len = 20
            
            //reason: '*** -[NSArray subarrayWithRange:]: range {100, 20} extends beyond bounds [0 .. 107]
            if loc + len > emotions.count{
                len = emotions.count - loc
            }
            
            let childArray = (emotions as NSArray).subarrayWithRange(NSMakeRange(loc, len)) as! [EmotionModel]
            tempArr.append(childArray)
        }
        return tempArr
    }
    
    //定义一个默认数组的表情
    lazy var defaultEmotion: [EmotionModel] = {
        
        //拿到所有的默认表情
        return self.loadEmotionWithPath("default/info.plist")
    }()
    
    
    lazy var emojiEmotion: [EmotionModel] = {
        
        return self.loadEmotionWithPath("emoji/info.plist")
        
    }()
    
    lazy var lxhEmotion: [EmotionModel] = {
        
        
        return self.loadEmotionWithPath("lxh/info.plist")
    }()
    
    private func loadEmotionWithPath(filePath: String) -> [EmotionModel]{
        
        let path = self.loadBundle().pathForResource(filePath, ofType: nil)!
        
        let array = NSArray(contentsOfFile: path)!
        
        var tempArr = [EmotionModel]()
        
        for value in array{
            
            let model = EmotionModel(dic: value as! [String : AnyObject])
            
            //设置表情所对应的文件夹名字
            let folderName = (filePath as NSString).stringByDeletingLastPathComponent
            model.folderName = folderName
            
            tempArr.append(model)
        }
        return tempArr
        
    }
}
